# -*- coding: utf-8 -*-
import logging
import os


config_file = os.path.join('log')


# def singleton(cls):
#     instances = {}
#
#     def _singleton(*args, **kwargs):
#         if cls not in instances:
#             instances[cls] = cls(*args, **kwargs)
#         return instances[cls]
#
#     return _singleton


class Log:

    def __init__(self, level='DEBUG'):
        # 日志器对象
        self.log = logging.getLogger()
        self.log.setLevel(level)

    def console_handle(self, level='DEBUG'):
        """控制台处理器"""
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        # 处理器添加格式
        console_handler.setFormatter(self.get_formatter()[0])
        return console_handler

    def file_handle(self, level='DEBUG'):
        """文件处理器"""
        file_handler = logging.FileHandler(config_file, mode='a', encoding='utf-8')
        file_handler.setLevel(level)
        # 处理器添加格式
        file_handler.setFormatter(self.get_formatter()[1])
        return file_handler

    def get_formatter(self):
        """格式器"""
        console_fmt = logging.Formatter(
            fmt='[%(name)s] '
                '[%(levelname)s] '
                '[%(asctime)s] '
                # '[%(module)s] '
                # '[%(funcName)s] '
                # '[%(thread)d] '
                # '[%(threadName)s] '
                # '[%(process)d] '
                '[%(message)s]')
        file_fmt = logging.Formatter(
            fmt='[%(name)s] '
                '[%(levelname)s] '
                '[%(asctime)s] '
                '[%(module)s] '
                '[%(funcName)s] '
                '[%(thread)d] '
                '[%(threadName)s] '
                '[%(process)d] '
                '[%(message)s]')
        return console_fmt, file_fmt

    def get_log(self):
        # 日志添加控制台处理器
        self.log.addHandler(self.console_handle())
        # 日志器添加文件处理器
        self.log.addHandler((self.file_handle()))
        # 返回日志实例对象
        return self.log


log = Log()
logger = log.get_log()
